package com.sfx.concurrent.demo.concurrent.AtomicTest.MyUnSafe;


import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-01-19
 * Time: 17:21
 */
public class UnSafeTest {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        //通过反射获取私有成员变量theUnsafe
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);//允许获取私有变量
        //获取theUnsafe的成员变量的值get(哪一个对象) 静态变量不属于对象填写null就行
        Unsafe unsafe = (Unsafe) theUnsafe.get(null);
        System.out.println("unsafe对象 : " + unsafe);
        //获取域的偏移地址
        long idOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("id"));
        long nameOffset = unsafe.objectFieldOffset(Teacher.class.getDeclaredField("name"));
        //执行CAS操作
        Teacher teacher = new Teacher();
        System.out.println(unsafe.compareAndSwapInt(teacher, idOffset, 0, 1));
        System.out.println(unsafe.compareAndSwapObject(teacher, nameOffset, null, "李四"));
    }
}
class Teacher{
    volatile int id;
    volatile String name;
}